﻿namespace Benefactor.Services;
using Repositories;
using static Statics;
public class CardNoGenerator(IIssuedBenefitsCardRepository issuedBenefitsCardRepository) : ICardNoGenerator
{
    public async Task<string> GenerateAsync(
        string systemId,
        string benefitsCardId,
        int length = DefaultCardNoLength,
        string prefix = DefaultCardNoPrefix,
        CancellationToken token = default
    )
    {
        var random = new Random();
        var delta = GetDelta();
        var recentIssuedBenefitsCard = 
            await issuedBenefitsCardRepository
            .GetAllAsync(
                query => query
                    .Where(x => x.SystemId == systemId && 
                                x.BenefitsCardId == benefitsCardId)
                    .OrderByDescending(x => x.CreateTime)
                    .Take(20), 
                token
            );

        var maxCardNo =
            recentIssuedBenefitsCard.Count > 0
            ? recentIssuedBenefitsCard
                .Select(x => int.Parse(x.CardNo[prefix.Length..])).Max()
            : 0;
        int nextCardNo = maxCardNo + delta;
        var cardNo = GetCardNo().Replace(BadNumber, BadNumberReplacement);
        return cardNo;

        int GetDelta() => random.Next(1, 30);

        string GetCardNo() => prefix + nextCardNo.ToString($"D{length - prefix.Length}");
    }
}